///
/// Copyright © 2016-2022 The Thingsboard Authors
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///

import { Injectable } from '@angular/core';

import { Resolve, Router } from '@angular/router';

import {
  DateEntityTableColumn,
  EntityTableColumn,
  EntityTableConfig
} from '@home/models/entity/entities-table-config.models';
import { TranslateService } from '@ngx-translate/core';
import { DatePipe } from '@angular/common';
import { EntityType, entityTypeResources, entityTypeTranslations } from '@shared/models/entity-type.models';
import { EntityAction } from '@home/models/entity/entity-component.models';
import {IotConfig} from "@shared/models/iot-config.model";
import {IotConfigService} from "@core/http/iot-config.service";
import {IotConfigComponent} from "@home/pages/iot-config/iot-config.component";
import {IotConfigTabsComponent} from "@home/pages/iot-config/iot-config-tabs.component";
import { getCurrentAuthState } from '@core/auth/auth.selectors';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';

// 单机菜单链接，主查询结果页面 table
@Injectable()
export class IotConfigsTableConfigResolver implements Resolve<EntityTableConfig<IotConfig>> {

  private readonly config: EntityTableConfig<IotConfig> = new EntityTableConfig<IotConfig>();

  constructor(private iotConfigService: IotConfigService,
              private translate: TranslateService,
              private datePipe: DatePipe,
              private router: Router,
              private store: Store<AppState>) {

    this.config.entityType = EntityType.IOT_CONFIG;
    this.config.entityComponent = IotConfigComponent;
    this.config.entityTabsComponent = IotConfigTabsComponent;
    this.config.entityTranslations = entityTypeTranslations.get(EntityType.IOT_CONFIG);
    this.config.entityResources = entityTypeResources.get(EntityType.IOT_CONFIG);
    const authState = getCurrentAuthState(this.store);

    // 表头字段 列
    this.config.columns.push(
      new DateEntityTableColumn<IotConfig>('createdTime', 'common.created-time', this.datePipe, '150px'),
      new EntityTableColumn<IotConfig>('title', 'iot-config.title', '25%'),
      // new EntityTableColumn<IotConfig>('email', 'contact.email', '25%'),
      // new EntityTableColumn<IotConfig>('country', 'contact.country', '25%'),
      new EntityTableColumn<IotConfig>('city', 'contact.city', '25%')
    );

    // 每行明细 右侧的功能按钮
    this.config.cellActionDescriptors.push(
      {
        name: this.translate.instant('iot-config.manage-iot-config-users'),
        icon: 'account_circle',
        isEnabled: (iotConfig) => !iotConfig.additionalInfo || !iotConfig.additionalInfo.isPublic,
        onAction: ($event, entity) => this.manageIotConfigUsers($event, entity)
      },
      {
        name: this.translate.instant('iot-config.manage-iot-config-assets'),
        nameFunction: (iotConfig) => {
          return iotConfig.additionalInfo && iotConfig.additionalInfo.isPublic
          ? this.translate.instant('iot-config.manage-public-assets')
          : this.translate.instant('iot-config.manage-iot-config-assets');
        },
        icon: 'domain',
        isEnabled: (iotConfig) => true,
        onAction: ($event, entity) => this.manageIotConfigAssets($event, entity)
      },
      {
        name: this.translate.instant('iot-config.manage-iot-config-devices'),
        nameFunction: (iotConfig) => {
          return iotConfig.additionalInfo && iotConfig.additionalInfo.isPublic
            ? this.translate.instant('iot-config.manage-public-devices')
            : this.translate.instant('iot-config.manage-iot-config-devices');
        },
        icon: 'devices_other',
        isEnabled: (iotConfig) => true,
        onAction: ($event, entity) => this.manageIotConfigDevices($event, entity)
      }
      ,{
        name: this.translate.instant('iot-config.manage-iot-config-dashboards'),
        nameFunction: (iotConfig) => {
          return iotConfig.additionalInfo && iotConfig.additionalInfo.isPublic
            ? this.translate.instant('iot-config.manage-public-dashboards')
            : this.translate.instant('iot-config.manage-iot-config-dashboards');
        },
        icon: 'dashboard',
        isEnabled: (iotConfig) => true,
        onAction: ($event, entity) => this.manageIotConfigDashboards($event, entity)
      }
      );
    if (authState.edgesSupportEnabled) {
      this.config.cellActionDescriptors.push(
          {
          name: this.translate.instant('iot-config.manage-iot-config-edges'),
          nameFunction: (iotConfig) => {
            return iotConfig.additionalInfo && iotConfig.additionalInfo.isPublic
              ? this.translate.instant('iot-config.manage-public-edges')
              : this.translate.instant('iot-config.manage-iot-config-edges');
          },
          icon: 'router',
          isEnabled: (iotConfig) => true,
          onAction: ($event, entity) => this.manageIotConfigEdges($event, entity)
        }
      );
    }

    this.config.deleteEntityTitle = iotConfig => this.translate.instant('iot-config.delete-iot-config-title', { iotConfigTitle: iotConfig.title });
    this.config.deleteEntityContent = () => this.translate.instant('iot-config.delete-iot-config-text');
    this.config.deleteEntitiesTitle = count => this.translate.instant('iot-config.delete-iot-configs-title', {count});
    this.config.deleteEntitiesContent = () => this.translate.instant('iot-config.delete-iot-configs-text');

    this.config.entitiesFetchFunction = pageLink => this.iotConfigService.getIotConfigs(pageLink);
    this.config.loadEntity = id => this.iotConfigService.getIotConfig(id.id);
    this.config.saveEntity = iotConfig => this.iotConfigService.saveIotConfig(iotConfig);
    this.config.deleteEntity = id => this.iotConfigService.deleteIotConfig(id.id);
    this.config.onEntityAction = action => this.onIotConfigAction(action, this.config);
    this.config.deleteEnabled = (iotConfig) => iotConfig && (!iotConfig.additionalInfo || !iotConfig.additionalInfo.isPublic);
    this.config.entitySelectionEnabled = (iotConfig) => iotConfig && (!iotConfig.additionalInfo || !iotConfig.additionalInfo.isPublic);
    this.config.detailsReadonly = (iotConfig) => iotConfig && iotConfig.additionalInfo && iotConfig.additionalInfo.isPublic;
  }

  resolve(): EntityTableConfig<IotConfig> {
    this.config.tableTitle = this.translate.instant('iot-config.iot-configs');

    return this.config;
  }

  private openIotConfig($event: Event, iotConfig: IotConfig, config: EntityTableConfig<IotConfig>) {
    if ($event) {
      $event.stopPropagation();
    }
    const url = this.router.createUrlTree([iotConfig.id.id], {relativeTo: config.getActivatedRoute()});
    this.router.navigateByUrl(url);
  }

  manageIotConfigUsers($event: Event, iotConfig: IotConfig) {
    if ($event) {
      $event.stopPropagation();
    }
    this.router.navigateByUrl(`iotConfig/${iotConfig.id.id}/users`);
  }

  manageIotConfigAssets($event: Event, iotConfig: IotConfig) {
    if ($event) {
      $event.stopPropagation();
    }
    this.router.navigateByUrl(`iotConfig/${iotConfig.id.id}/assets`);
  }

  manageIotConfigDevices($event: Event, iotConfig: IotConfig) {
    if ($event) {
      $event.stopPropagation();
    }
    this.router.navigateByUrl(`iotConfig/${iotConfig.id.id}/devices`);
  }

  manageIotConfigDashboards($event: Event, iotConfig: IotConfig) {
    if ($event) {
      $event.stopPropagation();
    }
    this.router.navigateByUrl(`iotConfig/${iotConfig.id.id}/dashboards`);
  }

  manageIotConfigEdges($event: Event, iotConfig: IotConfig) {
    if ($event) {
      $event.stopPropagation();
    }
    this.router.navigateByUrl(`iotConfig/${iotConfig.id.id}/edgeInstances`);
  }

  onIotConfigAction(action: EntityAction<IotConfig>, config: EntityTableConfig<IotConfig>): boolean {
    switch (action.action) {
      case 'open':
        this.openIotConfig(action.event, action.entity, config);
        return true;
      case 'manageUsers':
        this.manageIotConfigUsers(action.event, action.entity);
        return true;
      case 'manageAssets':
        this.manageIotConfigAssets(action.event, action.entity);
        return true;
      case 'manageDevices':
        this.manageIotConfigDevices(action.event, action.entity);
        return true;
      case 'manageDashboards':
        this.manageIotConfigDashboards(action.event, action.entity);
        return true;
      case 'manageEdges':
        this.manageIotConfigEdges(action.event, action.entity);
        return true;
    }
    return false;
  }

}
